package com.example.demo09redisbloom.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@Slf4j
@Component
public class BloomFilterInitializer implements CommandLineRunner {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    public static final String REDIS_BLOOM__NAME = "bit";
    public final static int _1K = 1000;
    public final static int _1W = 10000;
    public final static int SIZE = 100 * _1W;


    @Resource(name = "bloomMAddRedisScript")
    private RedisScript<List> bloomMAddRedisScript;

    //在应用启动时，通过 CommandLineRunner 初始化布隆过滤器，并将100万数据加入过滤器中。
    @Override
    public void run(String... args) throws Exception {
        // 初始化布隆过滤器
        // 指令：BF.RESERVE {key} {error_rate} {capacity} [EXPANSION expansion]

        // 100万数据加入布隆过滤器
        long beginTime = System.currentTimeMillis();
        List<String> list = new ArrayList<>();
        list.add(REDIS_BLOOM__NAME);
        for (int i = 1; i <= SIZE; i++) {
            list.add(Integer.toString(i));
            if (i % (5 * _1K) == 0) {
                redisTemplate.execute(bloomMAddRedisScript, list);
                list.clear();
                list.add(REDIS_BLOOM__NAME);
            }
        }
        if (list.size() > 1) {
            redisTemplate.execute(bloomMAddRedisScript, list);
        }
        log.info("初始化布隆过滤器完成，添加数量：{}，耗时：{} ms", SIZE, (System.currentTimeMillis() - beginTime));


    }
}